<?php

namespace app\controller;

use support\Request;

use Workerman\Protocols\Ws;
use Workerman\Worker;
use Workerman\Connection\AsyncTcpConnection;

class IndexController
{
    protected  $ws;

    public function ws()
    {
        if (!$this->ws) {
            // 以websocket协议连接远程websocket服务器
            $this->ws = new AsyncTcpConnection("ws://127.0.0.1:8484");
        }

        // 每隔55秒向服务端发送一个opcode为0x9的websocket心跳(可选)
        $this->ws->websocketPingInterval = 55;

        // 设置http头(可选)
        $this->ws->headers = [
          'Cookie'   => 'PHPSID=82u98fjhakfusuanfnahfi; token=2hf9a929jhfihaf9i',
          'OtherKey' => 'values'
        ];

        // 设置数据类型(可选)
        $this->ws->websocketType = Ws::BINARY_TYPE_BLOB; // BINARY_TYPE_BLOB为文本 BINARY_TYPE_ARRAYBUFFER为二进制

        // 当TCP完成三次握手后(可选)
        $this->ws->onConnect = function($connection){
            echo "tcp connected\n";
        };

        // 当websocket完成握手后(可选)
        $this->ws->onWebSocketConnect = function(AsyncTcpConnection $con, $response) {
            echo $response;
            $con->send('hello');
        };

        // 远程websocket服务器发来消息时
        $this->ws->onMessage = function($connection, $data){
            echo "recv: $data\n";
        };

        // 连接上发生错误时，一般是连接远程websocket服务器失败错误(可选)
        $this->ws->onError = function($connection, $code, $msg){
            echo "error: $msg\n";
        };

        // 当连接远程websocket服务器的连接断开时(可选，建议加上重连)
        $this->ws->onClose = function($connection){
            echo "connection closed and try to reconnect\n";
            // 如果连接断开，1秒后重连
            $connection->reConnect(1);
        };

        // 设置好以上各种回调后，执行连接操作
        $this->ws->connect();
    }

    public function index(Request $request)
    {
        $user = $request->session()->get('user');
        $id = $user["id"];
        $user = json_encode($user, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
        return view('user/index', ["id"=>$id, "user"=>$user]);
    }
}
